/*
 *  Copyright (C) 2011 JiangHongTiao <jjurco.sk_gmail.com>
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package sk.lieskove.jianghongtiao.websearch.api.google.search;

import org.json.JSONException;
import org.json.JSONObject;
import sk.lieskove.jianghongtiao.common.exceptions.HTTPResponseException;
import sk.lieskove.jianghongtiao.common.network.HTTPResponseStatusCode;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author xjuraj
 */
public class GWSResponseImpl implements GWSResponse{
    private JSONObject wsResult;
    private GWSResponseData responseData;
    private String responseDetails;
    private HTTPResponseStatusCode responseStatus;

    public GWSResponseImpl(JSONObject wsResult) throws JSONException, HTTPResponseException {
        if(wsResult == null){
            throw new NullPointerException("JSON object is null.");
        }
        this.wsResult = wsResult;
        parseWSResult(wsResult);
    }

    public GWSResponseData getResponseData() {
        return responseData;
    }

    public String responseDetails() {
        return responseDetails;
    }

    public HTTPResponseStatusCode responseStatus() {
        return responseStatus;
    }

    private void parseWSResult(JSONObject wsResult) throws JSONException, HTTPResponseException {
        responseDetails = wsResult.getString("responseDetails");
        try {
            responseStatus = new HTTPResponseStatusCode(wsResult.getInt("responseStatus"));
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(GWSResponseImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        if(responseStatus.isServerError() || responseStatus.isClientError()){
            throw new HTTPResponseException("Retrieving google results error. ", responseStatus);
        }
        responseData = new GWSResponseDataImpl(wsResult.getJSONObject("responseData"));
    }



}
